package parsers;

import database.UserData;
import entity.Client;
import entity.Clients;
import logger.LoggerManager;
import resurses.LoggerMessage;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

/**
 * Created by alexander.makalov on 22.10.2014.
 */
public class ClientXMLParser implements IParser {

    public ClientXMLParser(){}

    public ClientXMLParser(String path){
        pathToXMLFile = path;
    }

    @Override
    public void startParsing() {
        LoggerManager.getLogger().Log(String.format(LoggerMessage.START_XML_PARSING,pathToXMLFile), LoggerManager.LogLevel.INFO);
        if (pathToXMLFile != null) {
            try {
                FileReader reader = new FileReader(pathToXMLFile);
                JAXBContext jaxbContext = JAXBContext.newInstance(Clients.class);
                LoggerManager.getLogger().Log(LoggerMessage.START_PARSING_FILE, LoggerManager.LogLevel.INFO);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                Clients clients = (Clients) jaxbUnmarshaller.unmarshal(reader);
                clientList = clients.getClient();
                UserData.setFileExist(true);
                LoggerManager.getLogger().Log(LoggerMessage.END_PARSING_FILE, LoggerManager.LogLevel.INFO);
            } catch (FileNotFoundException|JAXBException e) {
                LoggerManager.getLogger().Log(e.getMessage(), LoggerManager.LogLevel.ERROR);
                UserData.setFileExist(false);
                //e.printStackTrace();
            }
        }
    }

    @Override
    public List<Client> getClientsList() {
        return clientList;
    }

    private String pathToXMLFile;
    private List<Client> clientList;
}
